package com.chunuo.gulimall.product.service.impl;

import com.chunuo.common.constant.ProductAttrEnum;
import com.chunuo.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.chunuo.gulimall.product.dao.AttrGroupDao;
import com.chunuo.gulimall.product.dao.CategoryDao;
import com.chunuo.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.chunuo.gulimall.product.entity.AttrGroupEntity;
import com.chunuo.gulimall.product.entity.CategoryEntity;
import com.chunuo.gulimall.product.service.AttrAttrgroupRelationService;
import com.chunuo.gulimall.product.vo.AttrVo;
import com.chunuo.gulimall.product.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chunuo.common.utils.PageUtils;
import com.chunuo.common.utils.Query;

import com.chunuo.gulimall.product.dao.AttrDao;
import com.chunuo.gulimall.product.entity.AttrEntity;
import com.chunuo.gulimall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    private AttrAttrgroupRelationDao relationDao;

    @Autowired
    private AttrGroupDao attrGroupDao;

    @Autowired
    private CategoryDao categoryDao;

    @Autowired
    private CategoryService categoryService;



    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 属性查询一页数据
     * @param params
     * @param catelogId
     * @param type
     * @return
     */
    @Override
    public PageUtils queryBaseAttrPage(Map<String, Object> params, Long catelogId, String type) {
        //查询条件中，判断attr_type 是 base的话，是基本数据   val：1
        // sale是销售数据  val：0
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>().
                eq("attr_type",type.equalsIgnoreCase("base")?
                        ProductAttrEnum.ATTR_TYPE_BASE.getCode() :
                        ProductAttrEnum.ATTR_TYPE_SALE.getCode());

        if(catelogId != 0){
            wrapper.eq("catelog_id",catelogId);
        }
//华为 HUAWEI P30 Pro 超感光徕卡四摄10倍混合变焦麒麟980芯片屏内指纹 8GB+256GB赤茶橘全网通版双4G手机
        //【直降400，到手价3599】买5G手机，4000万超感光徕卡影像屏内指纹；爆款至高立省800》
        String key = (String) params.get("key");

        if(key!=null&&!key.isEmpty()){
            wrapper.and((obj)->{
                obj.eq("attr_id",key).or().like("attr_name",key);
            });
        }

        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper
        );
        PageUtils pageUtils = new PageUtils(page);

        //从分页中获取到list集合
        List<AttrEntity> records = page.getRecords();
        //映射list集合，最后封装成AttrVo 实体类
        List<AttrVo> attrVos = records.stream().map((attrEntity) -> {
            //因为entity是对应数据表的，而vo是对应view的，因此再回响给前端的时候，要用vo的实体类
            AttrVo attrVo = new AttrVo();
            //把entity的属性值都赋给vo实体类
            BeanUtils.copyProperties(attrEntity, attrVo);

            //查询分组(name)

            //由于数据库表中并没有定义分组的id，而是使用了中间表(多对多）
            //查询中间表，获取有attr_id 相等的   ===   字段有：  id  attr_id  attr_group_id  attr_sort
            //注意：销售数据没有分组
            if("base".equalsIgnoreCase(type)){
                AttrAttrgroupRelationEntity attrAttrgroupRelationEntity =
                        relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrVo.getAttrId()));
                //attrAttrgroupRelationEntity不能为null并且存在attr_group_id
                if (attrAttrgroupRelationEntity != null && attrAttrgroupRelationEntity.getAttrGroupId() != null) {
                    //根据id查询到name
                    AttrGroupEntity attrGroupEntity =
                            attrGroupDao.selectOne(new QueryWrapper<AttrGroupEntity>().eq("attr_group_id", attrAttrgroupRelationEntity.getAttrGroupId()));
                    attrVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }


            //查询分类(name)
            CategoryEntity categoryEntity = categoryDao.selectById(attrVo.getCatelogId());
            if (categoryEntity != null) {
                attrVo.setCatelogName(categoryEntity.getName());
            }

            return attrVo;
        }).collect(Collectors.toList());

        //最后将映射好的list覆盖原先的list
        pageUtils.setList(attrVos);

        return pageUtils;
    }

    /**
     * 属性获取一条数据
     * @param attrId
     * @return
     */
    @Override
    public AttrVo getAttrInfo(Long attrId) {
        AttrVo respVo = new AttrVo();
        //从数据库获取实体类
        AttrEntity attrEntity = this.getById(attrId);
        //把属性都赋给respVo
        BeanUtils.copyProperties(attrEntity,respVo);

        //1、设置分组信息
        //注意：销售数据没有分组
        if(respVo.getAttrType() == ProductAttrEnum.ATTR_TYPE_BASE.getCode()){
            AttrAttrgroupRelationEntity attrgroupRelation =
                    relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
            if(attrgroupRelation!=null){
                //获取分组id
                respVo.setAttrGroupId(attrgroupRelation.getAttrGroupId());
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupRelation.getAttrGroupId());
                if(attrGroupEntity!=null){
                    //获取分组名称
                    respVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
        }

        //2、设置分类信息

        //获取分类id
        Long catelogId = attrEntity.getCatelogId();
        //得到分类的全路径id
        Long[] catelogPath = categoryService.findParentPath(catelogId);
        respVo.setCatelogPath(catelogPath);

        //根据分类id查询分类数据
        CategoryEntity categoryEntity = categoryDao.selectById(catelogId);
        if(categoryEntity!=null){
            //获取分类的名称
            respVo.setCatelogName(categoryEntity.getName());
        }

        return respVo;
    }

    @Transactional
    @Override
    public void saveDetail(AttrVo attrVo) {
        AttrEntity attr = new AttrEntity();
        BeanUtils.copyProperties(attrVo,attr);
        baseMapper.insert(attr);
        log.info("attr = {}",attr);
        //注意：销售数据没有分组
        if (attrVo.getAttrType() == ProductAttrEnum.ATTR_TYPE_BASE.getCode()){
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrAttrgroupRelationEntity.setAttrId(attr.getAttrId());
            attrAttrgroupRelationEntity.setAttrGroupId(attrVo.getAttrGroupId());
            attrAttrgroupRelationEntity.setAttrSort(0);
            relationDao.insert(attrAttrgroupRelationEntity);
        }
    }

    /**
     * 根据分组id找到组下的所有属性
     * @param attrgroupId
     * @return
     */
    @Override
    public List<AttrEntity> getRelation(Long attrgroupId) {
        //从中间表中，找到含有分组id的所有表
        List<AttrAttrgroupRelationEntity> attrAttrgroupRelationEntityList =
                relationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().
                        eq("attr_group_id", attrgroupId));
        //映射出id封装为list
        List<Long> longs = attrAttrgroupRelationEntityList.stream().map((entity) -> {
            return entity.getAttrId();
        }).collect(Collectors.toList());

        if(longs == null || longs.size() == 0){
            return null;
        }

        //根据list找到所有的属性
        Collection<AttrEntity> attrEntities = this.listByIds(longs);

        return (List<AttrEntity>) attrEntities;
    }

    /**
     * 获取没有被关联的属性
     * @param params
     * @param attrgroupId
     * @return
     */
    @Override
    public PageUtils getNotRelation(Map<String, Object> params, Long attrgroupId) {
        //查询本分组，为得到本分组的分类id
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupId);

        //必须本分类的id，况且attr_type必须是1 ==》 规格参数
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>().
                eq("catelog_id", attrGroupEntity.getCatelogId()).
                eq("attr_type", ProductAttrEnum.ATTR_TYPE_BASE.getCode());

        List<AttrEntity> attrEntityList = this.list(wrapper);
        log.info("attrEntityList = {}",attrEntityList);

        //映射出id，封装到list中
        List<Long> longList = attrEntityList.stream().map((entity) -> {
            return entity.getAttrId();
        }).collect(Collectors.toList());
        log.info("longList = {}",longList);

        //查询出已经被选过的attr，也就是说 在关联表中存在的longList
        List<AttrAttrgroupRelationEntity> attrAttrgroupRelationEntityList =
                relationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_id", longList).ne("attr_group_id","null"));

        //然后将已经选过的attrid也映射封装到list中
        List<Long> attr = attrAttrgroupRelationEntityList.stream().map((entity) -> {
            return entity.getAttrId();
        }).collect(Collectors.toList());
        log.info("attr = {}",attr);

        //最后只要查询全部的数据中，不包含 attr（已经选过的） 即可
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper.notIn("attr_id", attr)
        );
        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void updateDetail(AttrVo attrVo) {
        AttrEntity attr = new AttrEntity();
        BeanUtils.copyProperties(attrVo,attr);
        this.updateById(attr);

        AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
        //注意：销售数据没有分组
        if(attrVo.getAttrType() == ProductAttrEnum.ATTR_TYPE_BASE.getCode()){
            if(attrAttrgroupRelationEntity == null){
                attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
                attrAttrgroupRelationEntity.setAttrId(attrVo.getAttrId());
                attrAttrgroupRelationEntity.setAttrGroupId(attrVo.getAttrGroupId());
                attrAttrgroupRelationEntity.setAttrSort(0);
                relationDao.insert(attrAttrgroupRelationEntity);
                return;
            }

            attrAttrgroupRelationEntity.setAttrGroupId(attrVo.getAttrGroupId());
            relationDao.updateById(attrAttrgroupRelationEntity);
        }

    }

}